package com.example.goodtrash.db;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.goodtrash.model.Recycle;

import java.util.ArrayList;
import java.util.List;

public class RecycleDB {
    public static  final String DB_NAME = "recycle_history";
    public  static final int VERSION = 1;
    public  static RecycleDB recycleDB;
    public SQLiteDatabase db;
    private RecycleDB(Context context){
        RecycleHelper recycleHelper=new RecycleHelper(context,DB_NAME,null,VERSION);
        db=recycleHelper.getWritableDatabase();
    }
    public synchronized static RecycleDB getInstance(Context context){
        if (recycleDB==null){
            recycleDB=new RecycleDB(context);
        }
        return recycleDB;
    }

    public void saveRecycle(Recycle recycle){
        if (recycle!=null){
            ContentValues values=new ContentValues();
            values.put("name",recycle.getName());
            values.put("type",recycle.getType());
            values.put("dataTime",recycle.getDataTime());
            db.insert("recycle",null,values);

        }
    }

    @SuppressLint("Range")
    public List<Recycle> loadRecycle(){
        List<Recycle> list=new ArrayList<>();
        Cursor cursor=db.query("recycle",null,null,null,null,null,null);
        if (cursor.moveToFirst()){
            do{
                Recycle recycle=new Recycle();
                recycle.setId(cursor.getInt(cursor.getColumnIndex("id")));
                recycle.setName(cursor.getString(cursor.getColumnIndex("name")));
                recycle.setType(cursor.getString(cursor.getColumnIndex("type")));
                recycle.setDataTime(cursor.getString(cursor.getColumnIndex("dataTime")));
                list.add(recycle);
            } while (cursor.moveToNext());
        }
        if (cursor!=null){
            cursor.close();
        }
        return list;
    }


    public void removeRecycle(Recycle recycle){
        String s=String.valueOf(recycle.getId());
        db.delete("recycle","id=?",new String[]{s});
    }
}


